<template>
  <div class="kit-analysis-container">
    <div class="header">
      <h2>工单工序齐套分析</h2>

      <div class="header-actions">
        <button class="refresh-btn" @click="refreshData" :disabled="workOrdersLoading">
          <span class="btn-icon">🔄</span>
          {{ workOrdersLoading ? '加载中...' : '刷新' }}
        </button>
        <button class="back-btn" @click="goBack">返回</button>
      </div>
    </div>
    

    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      正在初始化界面...
    </div>
    
    <!-- 工单数据加载错误状态 -->
    <div v-else-if="hasLoadError" class="error-state">
      <div class="error-content">
        <h3>🚫 无法加载工单数据</h3>
        <p>无法连接到服务器，请检查：</p>
        <ul>
          <li>网络连接是否正常</li>
          <li>服务器是否运行</li>
          <li>API端点配置是否正确</li>
        </ul>
        <div class="error-actions">
          <button class="retry-btn" @click="loadWorkOrders">
            <span class="btn-icon">🔄</span>
            重试
          </button>
        </div>
      </div>
    </div>
    
    <div v-else class="main-content">
      <div class="left-panel">
        <div v-if="workOrdersLoading" class="loading-indicator">
          <p>正在加载工单数据...</p>
        </div>
        <div v-else-if="workOrders.length === 0" class="empty-state">
          <p>暂无工单数据</p>
          <button class="retry-btn" @click="loadWorkOrders">
            <span class="btn-icon">🔄</span>
            重新加载
          </button>
        </div>
        <div v-else class="work-order-tree">
          <!-- 一级标题：masterplan + model -->
          <div v-for="level1 in hierarchicalData" :key="level1.id" class="level1-section">
            <div class="tree-item level1-item" @click="toggleExpand(level1.id)">
              <span class="arrow" :class="{ expanded: expanded[level1.id] }">▷</span>
              <span class="level1-title">
                <div @mousedown="(event) => startDrag(event, event.currentTarget.parentElement)" @click.stop>{{ level1.title }}</div>
              </span>
            </div>
            
            <!-- 二级标题：orderno -->
            <div v-show="expanded[level1.id]" class="level2-container">
              <div v-for="level2 in level1.children" :key="level2.id" class="level2-section">
                <div class="tree-item level2-item" @click="toggleExpand(level2.id)">
                  <span class="arrow" :class="{ expanded: expanded[level2.id] }">▷</span>
                  <input 
                    type="checkbox" 
                    class="work-order-checkbox" 
                    :checked="checkedWorkOrders[level2.id]" 
                    @change="toggleWorkOrderCheck(level2.id)" 
                    @click.stop
                  />
                  <span class="level2-title">
                    <div @mousedown="(event) => startDrag(event, event.currentTarget.parentElement)" @click.stop>{{ level2.title }}</div>
                  </span>
                  <button class="analysis-btn small" @click.stop="performAnalysis(level2.id, $event)" :disabled="!hasCheckedWorkOrders">齐套分析</button>
                </div>
                
                <!-- 三级标题：workno (第一个-之后的部分) -->
                <div v-show="expanded[level2.id]" class="level3-container">
                  <div v-for="level3 in level2.children" :key="level3.id" class="tree-item level3-item">
                    <span class="level3-title">{{ level3.title }}</span>
                    <span class="workname">{{ level3.workname }}</span>
                    <button class="analysis-btn small" @click="performAnalysis(level3.id, $event)" :disabled="!hasCheckedWorkOrders">齐套分析</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="right-panel" ref="rightPanel">
        <!-- 动态定位的表格容器 -->
        <div v-if="hasAnalysisData && materialData.length > 0" class="material-table-container" :style="{ marginTop: tableTopOffset + 'px' }">
          <div class="material-table" ref="materialTable">
            <div class="table-header">
              <h3>{{ currentAnalysisInfo ? currentAnalysisInfo + ' | ' : '' }}齐套状态说明</h3>
              <div v-if="currentAnalysisInfo" class="analysis-info">
                <span class="info-label">当前分析：</span>
                <span class="info-content">{{ currentAnalysisInfo }}</span>
              </div>
            </div>
            <table>
              <thead>
                <tr>
                  <th v-if="showWorkOrderColumn">工单号</th>
                  <th>物料</th>
                  <th>需求数量</th>
                  <th>齐套状态</th>
                  <th>已齐套数</th>
                  <th>未齐套原因</th>
                  <th>缺料数量</th>
                  <th>U9库存总数量</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in materialData" :key="index">
                  <td v-if="showWorkOrderColumn" class="workorder-col">
                    <div @mousedown="(event) => startDrag(event, event.currentTarget.parentElement)">{{ item.workOrderNo || '-' }}</div>
                  </td>
                  <td class="material-col">
                    <div @mousedown="(event) => startDrag(event, event.currentTarget.parentElement)">{{ item.material || '-' }}</div>
                  </td>
                  <td class="quantity-col">{{ item.required || '-' }}</td>
                  <td class="status-col">{{ item.status }}</td>
                  <td class="completed-col">{{ item.completed || '-' }}</td>
                  <td class="reason-col">{{ item.reasonTag || '-' }}</td>
                  <td class="unused-col">{{ item.lackQty || '0' }}</td>
                  <td class="u9qty-col">{{ item.u9StoreQty || '0' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div v-else-if="!hasAnalysisData" class="no-analysis-hint">
          <p>请点击左侧的"齐套分析"按钮来查看物料齐套状态</p>
        </div>
        
        <!-- 缺少工序字段 -->
        
        <div v-else class="error-analysis">
          <p>缺少工序字段，无法进行齐套分析</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { apiRequest, getApiBaseUrl, getApiEndpoint, getSMISInventory, getU9Inventory, performKitAnalysis, getSMISWorkOrderMaterials } from '../utils/api.js'

const router = useRouter()
const route = useRoute()

// 获取查询参数中的MODocNos
const targetMODocNos = ref(route.query.moDocNos ? route.query.moDocNos.split(',') : null)

// 调试信息：打印接收到的参数
console.log('KitAnalysis.vue 接收到的路由参数:', route.query)
console.log('解析后的 targetMODocNos:', targetMODocNos.value)
const workOrders = ref([])
const smisInventory = ref([])
const u9Inventory = ref([])
// 配料数据现在直接从工单数据中获取
const loading = ref(true) // 主界面加载状态
const workOrdersLoading = ref(false) // 工单数据加载状态
const expanded = reactive({})
const checkedWorkOrders = reactive({}) // 工单勾选状态
const materialData = ref([])
const rightPanel = ref(null)
const materialTable = ref(null)

const tableTopOffset = ref(0)
const hasAnalysisData = ref(false) // 跟踪是否已经有分析数据
const analysisSession = ref(null) // 分析会话ID，用于跟踪分析状态
const hasLoadError = ref(false) // 跟踪加载错误状态
const currentAnalysisInfo = ref('') // 当前分析的信息描述

// 拖拽滚动相关状态
const isDragging = ref(false)
const dragStartX = ref(0)
const dragStartScrollLeft = ref(0)
const currentDragElement = ref(null)

// 可配置的API端点
const API_BASE_URL = getApiBaseUrl()
// 使用统一的API端点配置
const API_ENDPOINT = getApiEndpoint('WORK_ORDERS_FROM_TXT')

// U9响应数据解析函数
const parseResponseData = (responseData) => {
  if (!responseData) return []

  let dataArray = []

  try {
    // 检查Data字段是否为字符串（需要解析）还是已经是对象
    if (responseData.Data && typeof responseData.Data === 'string') {
      dataArray = JSON.parse(responseData.Data)
    } else if (responseData.Data && Array.isArray(responseData.Data)) {
      dataArray = responseData.Data
    } else if (Array.isArray(responseData)) {
      dataArray = responseData
    } else if (responseData.d && responseData.d.Data) {
      if (typeof responseData.d.Data === 'string') {
        dataArray = JSON.parse(responseData.d.Data)
      } else {
        dataArray = responseData.d.Data
      }
    }

    // 确保 dataArray 是数组
    if (!Array.isArray(dataArray)) {
      return []
    }

    return dataArray
  } catch (error) {
    return []
  }
}

// 计算属性：按层级结构组织数据
const hierarchicalData = computed(() => {
  const result = []
  
  // 调试信息：打印工单数据总数
  console.log('=== KitAnalysis 数据匹配调试 ===')
  console.log('工单数据总数:', workOrders.value.length)
  console.log('目标MODocNos:', targetMODocNos.value)
  
  // 定义需要显示的工序状态
  const validStates = ['创建', '执行中', '已下达']
  
  // 按 masterplan 分组 (一级标题)
  const grouped = {}
  
  workOrders.value.forEach((order, index) => {
    // 检查工单是否包含有效状态的工序
    const hasValidWork = order.works && order.works.some(work => 
      validStates.includes(work.state)
    )
    
    // 调试信息：打印每个工单的基本信息
    console.log(`工单 ${index + 1}/${workOrders.value.length}:`, {
      orderno: order.orderno,
      masterplan: order.masterplan,
      hasValidWork: hasValidWork,
      worksCount: order.works ? order.works.length : 0
    })
    
    // 如果指定了targetMODocNos，只显示masterplan字段与targetMODocNos中任一匹配的工单
    let shouldShow = hasValidWork
    if (targetMODocNos.value && targetMODocNos.value.length > 0 && hasValidWork) {
      // 处理masterplan字段：如果有空格，只保留空格前的内容进行比较
      const masterplanForComparison = (order.masterplan || '').trim()
      const spaceIndex = masterplanForComparison.indexOf(' ')
      const masterplanPrefix = spaceIndex !== -1 ? masterplanForComparison.substring(0, spaceIndex) : masterplanForComparison
      
      // 检查masterplan是否与任一targetMODocNo匹配
      const isMatch = targetMODocNos.value.includes(masterplanPrefix)
      shouldShow = isMatch
      
      // 调试信息：打印匹配过程
      console.log(`  匹配检查:`, {
        originalMasterplan: order.masterplan,
        masterplanPrefix: masterplanPrefix,
        targetMODocNos: targetMODocNos.value,
        isMatch: isMatch,
        shouldShow: shouldShow
      })
    }
    
    // 只有包含有效工序且符合过滤条件的工单才会被显示
    if (shouldShow) {
      const level1Key = order.masterplan || '未知计划'
      
      if (!grouped[level1Key]) {
        grouped[level1Key] = []
      }
      
      grouped[level1Key].push(order)
    }
  })
  
  // 转换为层级结构
  Object.entries(grouped).forEach(([planModel, orders]) => {
    const level1Item = {
      id: planModel,
      title: planModel,
      type: 'level1',
      children: []
    }
    
    orders.forEach(order => {
      const level2Item = {
        id: order.orderno,
        title: order.orderno,
        type: 'level2',
        children: []
      }
      
      // 添加三级标题（works中的workno，只显示有一个"-"的工序且状态有效）
      if (order.works && order.works.length > 0) {
        const validWorks = []
        
        order.works.forEach(work => {
          // 统计workno中"-"的数量
          const dashCount = (work.workno.match(/-/g) || []).length
          
          // 只显示有一个"-"的工序且状态在有效列表中
          if (dashCount === 1 && validStates.includes(work.state)) {
            const worknoDisplay = work.workno.substring(work.workno.indexOf('-') + 1)
            
            validWorks.push({
              id: work.workno,
              title: worknoDisplay,
              workname: work.workname,
              type: 'level3',
              sortKey: worknoDisplay // 用于排序的键
            })
          }
        })
        
        // 对M编号进行排序
        validWorks.sort((a, b) => {
          // 提取M后面的数字进行比较
          const getNumber = (title) => {
            const match = title.match(/M(\d+)/)
            return match ? parseInt(match[1]) : 0
          }
          
          return getNumber(a.sortKey) - getNumber(b.sortKey)
        })
        
        // 添加排序后的工序
        validWorks.forEach(work => {
          level2Item.children.push({
            id: work.id,
            title: work.title,
            workname: work.workname,
            type: work.type
          })
        })
      }
      
      level1Item.children.push(level2Item)
    })
    
    result.push(level1Item)
  })
  
  return result
})

// 计算属性：是否显示工单号列（当有多个工单的齐套分析结果时显示）
const showWorkOrderColumn = computed(() => {
  if (!materialData.value || materialData.value.length === 0) {
    return false
  }
  
  // 检查是否有多个不同的工单号
  const uniqueWorkOrders = [...new Set(materialData.value.map(item => item.workOrderNo).filter(Boolean))]
  return uniqueWorkOrders.length > 1
})

// 计算属性：检查是否有工单被勾选
const hasCheckedWorkOrders = computed(() => {
  return Object.values(checkedWorkOrders).some(checked => checked)
})

// 从API获取数据
const loadWorkOrders = async () => {
  try {
    workOrdersLoading.value = true
    hasLoadError.value = false // 重置错误状态
    
    // 使用API工具进行请求
    const response = await apiRequest(API_ENDPOINT, {
      method: 'GET'
    })
    
    const data = await response.json()
    
    // 处理 Python API 服务器的响应格式
    if (data && data.success && Array.isArray(data.data)) {
      workOrders.value = data.data
    } else if (data && data.success && data.data) {
      // 如果data.data不是数组，尝试转换
      const dataArray = Array.isArray(data.data) ? data.data : [data.data]
      workOrders.value = dataArray
    } else {
      // 处理其他格式或错误
      const errorMsg = data?.message || '数据格式错误'
      throw new Error(errorMsg)
    }
    
  } catch (err) {
    hasLoadError.value = true // 设置错误状态
    workOrders.value = []
  } finally {
    workOrdersLoading.value = false
  }
}

const goBack = () => {
  router.push('/')
}

// 清除过滤器
const clearFilter = () => {
  targetMODocNos.value = null
  // 更新路由，移除查询参数
  router.replace({ path: '/kit-analysis' })
}

// 手动刷新数据
const refreshData = async () => {
  // 重置分析状态
  hasAnalysisData.value = false
  materialData.value = []
  analysisSession.value = null
  hasLoadError.value = false
  
  // 重置库存数据
  smisInventory.value = []
  u9Inventory.value = []
  
  await loadWorkOrders()
}

const toggleExpand = (key) => {
  expanded[key] = !expanded[key]
}

// 切换工单勾选状态
const toggleWorkOrderCheck = (workOrderId) => {
  checkedWorkOrders[workOrderId] = !checkedWorkOrders[workOrderId]
}

// 加载SMIS配料岛库存数据
const loadSMISInventory = async () => {
  try {
    const response = await getSMISInventory()
    
    if (response && response.success && response.data) {
      smisInventory.value = Array.isArray(response.data) ? response.data : [response.data]
    } else {
      smisInventory.value = []
    }
  } catch (error) {
    console.error('加载SMIS配料岛库存数据失败:', error.message)
    smisInventory.value = []
  }
}

// 加载U9库存数据
const loadU9Inventory = async (materials = []) => {
  try {
    if (materials.length === 0) {
      u9Inventory.value = []
      return
    }
    
    const response = await getU9Inventory(materials)
    
    if (response) {
      u9Inventory.value = Array.isArray(response) ? response : [response]
    } else {
      u9Inventory.value = []
    }
  } catch (error) {
    console.error('加载U9库存数据失败:', error.message)
    u9Inventory.value = []
  }
}

// 从工单数据中提取配料信息
const extractMaterialsFromWorkOrder = (workOrderId, workProcessId = null) => {
  const materials = []
  
  // 查找对应的工单
  const targetWorkOrder = workOrders.value.find(order => order.orderno === workOrderId)
  if (!targetWorkOrder) {
    return materials
  }
  
  // 从inputMaterialRequirements字段中提取物料信息
  if (targetWorkOrder.inputMaterialRequirements && Array.isArray(targetWorkOrder.inputMaterialRequirements)) {
    targetWorkOrder.inputMaterialRequirements.forEach(material => {
      if (material.materialdefinition && material.quantity) {
        // 如果指定了工序ID，需要检查work字段匹配
        if (workProcessId) {
          // 检查material.work字段，取第二个-之前的部分
          if (material.work) {
            const workParts = material.work.split('-')
            if (workParts.length >= 2) {
              const workPrefix = workParts[0] + '-' + workParts[1] // 取第二个-之前的部分
              // 检查是否与工序ID匹配
              if (workPrefix === workProcessId) {
                materials.push({
                  workOrderNo: targetWorkOrder.orderno,
                  materialCode: material.materialdefinition,
                  materialDescription: material.materialdefinition, // 使用materialdefinition作为物料名称
                  spec: material.spec || '',
                  requiredQuantity: parseFloat(material.quantity) || 0,
                  workProcess: workProcessId // 添加工序信息
                })
              }
            }
          }
        } else {
          // 如果没有指定工序ID，提取所有物料（原有逻辑）
          materials.push({
            workOrderNo: targetWorkOrder.orderno,
            materialCode: material.materialdefinition,
            materialDescription: material.materialdefinition, // 使用materialdefinition作为物料名称
            spec: material.spec || '',
            requiredQuantity: parseFloat(material.quantity) || 0
          })
        }
      }
    })
  }
  
  return materials
}

// 执行齐套分析（整合数据获取）
const executeKitAnalysis = async (workOrderId = null, materials = [], workProcessId = null) => {
  try {
    // 先加载SMIS配料岛库存数据
    await loadSMISInventory()
    
    // 预分析：确定哪些物料需要查询U9库存
    const materialsNeedingU9Query = []
    let relevantConfigData = []
    
    if (workOrderId) {
      // 从工单数据中提取物料信息
      relevantConfigData = extractMaterialsFromWorkOrder(workOrderId, workProcessId)
    }
    
    // 获取当前工单的masterplan（用于匹配SMIS配料岛数据）
    let masterplanForMatching = null
    if (workOrderId) {
      const targetWorkOrder = workOrders.value.find(order => order.orderno === workOrderId)
      if (targetWorkOrder) {
        const originalMasterplan = targetWorkOrder.masterplan || ''
        masterplanForMatching = originalMasterplan.trim()
        const spaceIndex = masterplanForMatching.indexOf(' ')
        if (spaceIndex !== -1) {
          masterplanForMatching = masterplanForMatching.substring(0, spaceIndex)
        }
      }
    }
    
    // 预检查每个物料的配料岛库存情况
    for (const configItem of relevantConfigData) {
      const materialCode = configItem.materialCode
      const requiredQty = configItem.requiredQuantity
      
      // 在SMIS配料岛库存中查找匹配的物料
      let smisMatches = []
      if (masterplanForMatching) {
        smisMatches = smisInventory.value.filter(item => {
          const masterplanMatch = item.masterplancode === masterplanForMatching
          const materialMatch = item.materialcode === materialCode
          return masterplanMatch && materialMatch
        })
      } else {
        smisMatches = smisInventory.value.filter(item => 
          item.materialcode === materialCode
        )
      }
      
      // 计算SMIS配料岛总库存
      let smisTotal = 0
      smisMatches.forEach(item => {
        if (typeof item.total === 'number') {
          smisTotal += item.total
        }
      })
      
      // 只有配料岛库存不足的物料才需要查询U9库存
      if (smisTotal < requiredQty) {
        materialsNeedingU9Query.push(materialCode)
      }
    }
    
    // 只查询需要的物料的U9库存
    if (materialsNeedingU9Query.length > 0) {
      await loadU9Inventory(materialsNeedingU9Query)
    } else {
      u9Inventory.value = []
    }
    
    // 执行具体的齐套分析逻辑
    const analysisResults = performDetailedKitAnalysis(workOrderId, workProcessId)
    
    return {
      success: true,
      smisInventoryCount: smisInventory.value.length,
      u9InventoryCount: u9Inventory.value.length,
      configurationDataCount: relevantConfigData.length,
      analysisResults: analysisResults,
      analysisTimestamp: new Date().toISOString()
    }
  } catch (error) {
    console.error('齐套分析执行失败:', error)
    throw error
  }
}

// 执行多个工单的齐套分析（汇总结果）
const executeKitAnalysisForWorkOrders = async (workOrderIds = null) => {
  try {
    
    if (!workOrderIds || workOrderIds.length === 0) {
      // 如果没有指定工单，进行全部分析
      return await executeKitAnalysis(null, [], null)
    }
    
    // 检查是否有工序ID参数
    const workProcessId = workOrderIds.workProcessId || null
    
    // 如果只有一个工单，直接调用单工单分析
    if (workOrderIds.length === 1) {
      return await executeKitAnalysis(workOrderIds[0], [], workProcessId)
    }
    
    // 多个工单分析：汇总所有工单的分析结果
    
    // 提取所有相关工单的物料清单用于U9查询
    let allMaterialCodes = []
    for (const workOrderId of workOrderIds) {
      const materials = extractMaterialsFromWorkOrder(workOrderId)
      const materialCodes = materials.map(item => item.materialCode).filter(Boolean)
      allMaterialCodes.push(...materialCodes)
    }
    allMaterialCodes = [...new Set(allMaterialCodes)] // 去重
    
    // 并行加载SMIS配料岛库存和U9库存数据
    await Promise.all([
      loadSMISInventory(),
      loadU9Inventory(allMaterialCodes)
    ])
    
    // 汇总所有工单的齐套分析结果
    const allAnalysisResults = []
    
    for (const workOrderId of workOrderIds) {
      const results = performDetailedKitAnalysis(workOrderId)
      
      // 给每个结果添加工单号标识
      const resultsWithWorkOrder = results.map(result => ({
        ...result,
        workOrderNo: workOrderId // 添加工单号字段以便识别
      }))
      
      allAnalysisResults.push(...resultsWithWorkOrder)
    }
    
    // 按照齐套状态排序：缺料 > 未领用 > 齐套，然后按工单号和物料编码排序
    allAnalysisResults.sort((a, b) => {
      // 首先按优先级排序（缺料置顶）
      if (a.sortPriority !== b.sortPriority) {
        return a.sortPriority - b.sortPriority
      }
      // 其次按工单号排序
      if (a.workOrderNo !== b.workOrderNo) {
        return a.workOrderNo.localeCompare(b.workOrderNo)
      }
      // 最后按物料编码排序
      return a.material.localeCompare(b.material)
    })
    
    return {
      success: true,
      smisInventoryCount: smisInventory.value.length,
      u9InventoryCount: u9Inventory.value.length,
      configurationDataCount: allMaterialCodes.length,
      analysisResults: allAnalysisResults,
      analysisTimestamp: new Date().toISOString(),
      workOrderCount: workOrderIds.length
    }
  } catch (error) {
    console.error('多工单齐套分析执行失败:', error)
    throw error
  }
}

// 执行详细的齐套分析逻辑
const performDetailedKitAnalysis = (workOrderId, workProcessId = null) => {
  // 从工单数据中提取物料信息
  let relevantConfigData = []
  if (workOrderId) {
    relevantConfigData = extractMaterialsFromWorkOrder(workOrderId, workProcessId)
  }
  
  // 如果没有相关配料数据，返回提示信息
  if (relevantConfigData.length === 0) {
    const message = workOrderId ? 
      `工单 ${workOrderId} 中未找到物料定义数据` :
      '未找到物料定义数据'
    
    return [{
      material: '无物料数据',
      spec: '-',
      required: '-',
      status: '无数据',
      statusClass: 'incomplete',
      completed: '-',
      reasonTag: '数据缺失',
      unused: '-'
    }]
  }
  
  // 查找对应的工单数据
  let targetWorkOrder = null
  if (workOrderId) {
    for (const order of workOrders.value) {
      if (order.orderno === workOrderId) {
        targetWorkOrder = order
        break
      }
    }
  }
  
  // 对每个物料进行齐套分析
  const analysisResults = []
  
  // 获取当前工单的masterplan（用于匹配SMIS配料岛数据）
  let masterplanForMatching = null
  if (workOrderId && targetWorkOrder) {
    // 处理masterplan字段：如果有空格，只保留空格前的内容
    const originalMasterplan = targetWorkOrder.masterplan || ''
    masterplanForMatching = originalMasterplan.trim()
    const spaceIndex = masterplanForMatching.indexOf(' ')
    if (spaceIndex !== -1) {
      masterplanForMatching = masterplanForMatching.substring(0, spaceIndex)
    }
  }
  
  for (const configItem of relevantConfigData) {
    const materialCode = configItem.materialCode
    const requiredQty = configItem.requiredQuantity
    const spec = configItem.spec || '-' // 规格信息
    
    // 在SMIS配料岛库存中查找匹配的物料
    let smisMatches = []
    
    if (masterplanForMatching) {
      // 如果有工单masterplan，则需要masterplancode和materialcode都匹配
      smisMatches = smisInventory.value.filter(item => {
        const masterplanMatch = item.masterplancode === masterplanForMatching
        const materialMatch = item.materialcode === materialCode
        return masterplanMatch && materialMatch
      })
    } else {
      // 如果没有工单masterplan（全部分析），只匹配materialcode
      smisMatches = smisInventory.value.filter(item => 
        item.materialcode === materialCode
      )
    }
    
    // 计算SMIS配料岛总库存
    let smisTotal = 0
    let smisUseStock = 0
    
    smisMatches.forEach(item => {
      if (typeof item.total === 'number') {
        smisTotal += item.total
      }
      if (typeof item.usestock === 'number') {
        smisUseStock += item.usestock
      }
    })
    
    // 在U9库存中查找匹配的物料
    const u9Matches = u9Inventory.value.filter(item => 
      item.ItemCode === materialCode || item.itemCode === materialCode
    )
    
    // 计算U9库存数量
    let u9StoreQty = 0
    u9Matches.forEach((item, index) => {
      // 使用统一的解析函数解析U9响应数据
      const dataArray = parseResponseData(item)
      
      if (dataArray.length > 0) {
        // 遍历数组中的每个对象，累加StoreQty
        dataArray.forEach((dataItem, dataIndex) => {
          if (dataItem && typeof dataItem === 'object' && dataItem.StoreQty !== undefined) {
            const storeQty = parseFloat(dataItem.StoreQty) || 0
            u9StoreQty += storeQty
          }
        })
      }
    })
    
    // 判断齐套状态
    let status = '未齐套'
    let statusClass = 'incomplete'
    let completed = 0
    let reasonTag = ''
    let reasonText = ''
    let unused = '0' // 缺料数量：已齐套为0，部分齐套/未齐套时为缺口，未领用时为0
    
    if (smisTotal >= requiredQty) {
      // 配料岛库存充足，已齐套
      status = '已齐套'
      statusClass = 'complete'
      completed = requiredQty // 已齐套数量就是需求数量
      reasonTag = '' // 已齐套时不显示原因标签
      reasonText = '' // 已齐套时不显示原因文本
      unused = '0' // 缺料数量为0
    } else {
      // 配料岛库存不足，需要查看U9库存
      const totalAvailable = smisTotal + u9StoreQty
      if (smisTotal > 0 && smisTotal < requiredQty) {
        status = '部分齐套'
        statusClass = 'partial'
        if (totalAvailable >= requiredQty) {
          reasonTag = '未领用'
          reasonText = `需从U9库存补充 ${requiredQty - smisTotal} 个`
          completed = smisTotal
          unused = '0' // 未领用时缺料数量为0
        } else {
          reasonTag = '缺料'
          const shortage = requiredQty - totalAvailable
          reasonText = `总库存${totalAvailable}不足，缺料 ${shortage} 个`
          completed = smisTotal
          const shortageAmount = requiredQty - totalAvailable
          unused = `${shortageAmount}` // 缺料状态下，缺料数量为数字
        }
      } else if (smisTotal === 0) {
        if (totalAvailable >= requiredQty) {
          status = '未齐套'
          statusClass = 'incomplete'
          reasonTag = '未领用'
          reasonText = `需从U9库存补充 ${requiredQty} 个`
          completed = 0
          unused = '0' // 未领用时缺料数量为0
        } else {
          status = '未齐套'
          statusClass = 'incomplete'
          reasonTag = '缺料'
          const shortage = requiredQty - totalAvailable
          reasonText = `总库存${totalAvailable}不足，缺料 ${shortage} 个`
          completed = 0
          const shortageAmount = requiredQty - totalAvailable
          unused = `${shortageAmount}` // 缺料状态下，缺料数量为数字
        }
      }
    }
    
    // 修正后的齐套状态判定逻辑说明:
    // 场景1: 配料岛库存充足 (smisTotal >= requiredQty)
    //   - 状态: "已齐套", 已齐套数: requiredQty, 未领用: "0"
    // 场景2: 配料岛有部分库存但不足 (0 < smisTotal < requiredQty)
    //   - 如果总库存充足: 状态: "部分齐套", 已齐套数: smisTotal, 未领用: requiredQty - smisTotal
    //   - 如果总库存不足: 状态: "部分齐套", 已齐套数: smisTotal, 未领用: "缺" + (requiredQty - totalAvailable)
    // 场景3: 配料岛无库存 (smisTotal = 0)
    //   - 如果U9库存充足: 状态: "未齐套", 已齐套数: 0, 未领用: requiredQty
    //   - 如果U9库存不足: 状态: "未齐套", 已齐套数: 0, 未领用: "缺" + (requiredQty - totalAvailable)

    // 缺料数量（新规则）
    let lackQty = '0'
    if (reasonTag === '缺料') {
      // 缺料时，缺料数量为数字（去掉“缺”字）
      if (unused.startsWith('缺')) {
        lackQty = unused.replace('缺', '')
      } else {
        lackQty = unused
      }
    } else if (reasonTag === '未领用') {
      // 未领用时，缺料数量为0
      lackQty = '0'
    } else {
      lackQty = '0'
    }

    analysisResults.push({
      material: materialCode,
      spec: spec, // 使用从Excel第3列提取的规格信息
      required: requiredQty.toString(),
      status: status,
      statusClass: statusClass,
      completed: completed.toString(),
      reasonTag: reasonTag,
      lackQty: lackQty, // 新增：缺料数量
      u9StoreQty: u9StoreQty.toString(), // 新增：U9库存总数量
      sortPriority: reasonTag === '缺料' ? 1 : (reasonTag === '未领用' ? 2 : 3) // 用于排序的优先级：缺料 > 未领用 > 齐套
    })
  }
  
  // 按照齐套状态排序：缺料 > 未领用 > 齐套
  analysisResults.sort((a, b) => {
    // 首先按优先级排序（缺料置顶）
    if (a.sortPriority !== b.sortPriority) {
      return a.sortPriority - b.sortPriority
    }
    // 其次按物料编码排序
    return a.material.localeCompare(b.material)
  })
  
  return analysisResults
}

// Helper函数：生成点击标题的描述信息
const getClickedTitleInfo = (workno) => {
  if (workno && typeof workno === 'object' && workno.type === 'level1') {
    return workno.id
  } else if (workno && typeof workno === 'string') {
    for (const level1 of hierarchicalData.value) {
      for (const level2 of level1.children) {
        if (level2.id === workno) {
          return level2.title
        }
        for (const level3 of level2.children) {
          if (level3.id === workno) {
            return level3.title
          }
        }
      }
    }
    return workno
  } else {
    return '全部工单'
  }
}

const performAnalysis = async (workno = null, event = null) => {
  // 生成唯一的分析会话ID
  const sessionId = `analysis_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
  analysisSession.value = sessionId
  
  // 设置分析状态
  hasAnalysisData.value = true
  
  try {
    let analysisResults = []
    let analysisInfo = ''
    
    // 首先检查是否是三级标题分析（工序分析）
    let isLevel3Analysis = false
    if (workno && typeof workno === 'string') {
      // 检查是否是三级标题ID
      for (const level1 of hierarchicalData.value) {
        for (const level2 of level1.children) {
          for (const level3 of level2.children) {
            if (level3.id === workno) {
              isLevel3Analysis = true
              break
            }
          }
          if (isLevel3Analysis) break
        }
        if (isLevel3Analysis) break
      }
    }
    
    // 检查是否有勾选的工单（但三级标题分析优先）
    const checkedWorkOrderIds = Object.keys(checkedWorkOrders).filter(id => checkedWorkOrders[id])
    
    if (checkedWorkOrderIds.length > 0 && !isLevel3Analysis) {
       // 如果有勾选的工单且不是三级标题分析，先获取所有物料信息，然后调用齐套分析函数
       console.log('🔍 使用勾选的工单进行齐套分析:', checkedWorkOrderIds)
      
      // 收集所有物料信息
      const allMaterials = []
      
      for (const orderno of checkedWorkOrderIds) {
        try {
          const response = await getSMISWorkOrderMaterials(orderno)
          
          if (response && response.success && response.data) {
            const workOrders = Array.isArray(response.data) ? response.data : [response.data]
            
            // 从每个工单的inputMaterialRequirements中提取物料信息
            workOrders.forEach(workOrder => {
              if (workOrder.inputMaterialRequirements && Array.isArray(workOrder.inputMaterialRequirements)) {
                workOrder.inputMaterialRequirements.forEach(material => {
                  const requiredQty = parseFloat(material.quantity || material.qty || '0')
                  
                  allMaterials.push({
                    workOrderNo: workOrder.orderno || orderno,
                    materialCode: material.materialdefinition || '',
                    materialDescription: material.materialname || material.materialdefinition || '-',
                    spec: material.materialname || material.materialdefinition || '-',
                    requiredQuantity: requiredQty
                  })
                })
              }
            })
          }
        } catch (error) {
          console.error(`获取工单 ${orderno} 的物料数据失败:`, error)
        }
      }
      
      // 如果获取到物料信息，调用齐套分析函数
      if (allMaterials.length > 0) {
        // 先加载SMIS配料岛库存数据
        await loadSMISInventory()
        
        // 提取所有物料编码用于U9库存查询
        const materialCodes = [...new Set(allMaterials.map(item => item.materialCode).filter(Boolean))]
        
        // 加载U9库存数据
        await loadU9Inventory(materialCodes)
        
        // 对每个物料进行齐套分析
        for (const materialItem of allMaterials) {
          const materialCode = materialItem.materialCode
          const requiredQty = materialItem.requiredQuantity
          const spec = materialItem.spec
          const workOrderNo = materialItem.workOrderNo
          
          // 获取当前工单的masterplan（用于匹配SMIS配料岛数据）
          let masterplanForMatching = null
          const targetWorkOrder = workOrders.value.find(order => order.orderno === workOrderNo)
          if (targetWorkOrder) {
            const originalMasterplan = targetWorkOrder.masterplan || ''
            masterplanForMatching = originalMasterplan.trim()
            const spaceIndex = masterplanForMatching.indexOf(' ')
            if (spaceIndex !== -1) {
              masterplanForMatching = masterplanForMatching.substring(0, spaceIndex)
            }
          }
          
          // 在SMIS配料岛库存中查找匹配的物料
          let smisMatches = []
          if (masterplanForMatching) {
            smisMatches = smisInventory.value.filter(item => {
              const masterplanMatch = item.masterplancode === masterplanForMatching
              const materialMatch = item.materialcode === materialCode
              return masterplanMatch && materialMatch
            })
          } else {
            smisMatches = smisInventory.value.filter(item => 
              item.materialcode === materialCode
            )
          }
          
          // 计算SMIS配料岛总库存
          let smisTotal = 0
          smisMatches.forEach(item => {
            if (typeof item.total === 'number') {
              smisTotal += item.total
            }
          })
          
          // 在U9库存中查找匹配的物料
          const u9Matches = u9Inventory.value.filter(item => 
            item.ItemCode === materialCode || item.itemCode === materialCode
          )
          
          // 计算U9库存数量
          let u9StoreQty = 0
          u9Matches.forEach((item, index) => {
            const dataArray = parseResponseData(item)
            
            if (dataArray.length > 0) {
              dataArray.forEach((dataItem, dataIndex) => {
                if (dataItem && typeof dataItem === 'object' && dataItem.StoreQty !== undefined) {
                  const storeQty = parseFloat(dataItem.StoreQty) || 0
                  u9StoreQty += storeQty
                }
              })
            }
          })
          
          // 判断齐套状态
          let status = '未齐套'
          let statusClass = 'incomplete'
          let completed = 0
          let reasonTag = ''
          let lackQty = '0'
          
          if (smisTotal >= requiredQty) {
            // 配料岛库存充足，已齐套
            status = '已齐套'
            statusClass = 'complete'
            completed = requiredQty
            reasonTag = ''
            lackQty = '0'
          } else {
            // 配料岛库存不足，需要查看U9库存
            const totalAvailable = smisTotal + u9StoreQty
            if (smisTotal > 0 && smisTotal < requiredQty) {
              status = '部分齐套'
              statusClass = 'partial'
              if (totalAvailable >= requiredQty) {
                reasonTag = '未领用'
                completed = smisTotal
                lackQty = '0'
              } else {
                reasonTag = '缺料'
                completed = smisTotal
                const shortageAmount = requiredQty - totalAvailable
                lackQty = `${shortageAmount}`
              }
            } else if (smisTotal === 0) {
              if (totalAvailable >= requiredQty) {
                status = '未齐套'
                statusClass = 'incomplete'
                reasonTag = '未领用'
                completed = 0
                lackQty = '0'
              } else {
                status = '未齐套'
                statusClass = 'incomplete'
                reasonTag = '缺料'
                completed = 0
                const shortageAmount = requiredQty - totalAvailable
                lackQty = `${shortageAmount}`
              }
            }
          }
          
          analysisResults.push({
            workOrderNo: workOrderNo,
            material: materialCode,
            spec: spec,
            required: requiredQty.toString(),
            status: status,
            statusClass: statusClass,
            completed: completed.toString(),
            reasonTag: reasonTag,
            lackQty: lackQty,
            u9StoreQty: u9StoreQty.toString(),
            sortPriority: reasonTag === '缺料' ? 1 : (reasonTag === '未领用' ? 2 : 3)
          })
        }
        
        // 按照齐套状态排序：缺料 > 未领用 > 齐套
        analysisResults.sort((a, b) => {
          if (a.sortPriority !== b.sortPriority) {
            return a.sortPriority - b.sortPriority
          }
          if (a.workOrderNo !== b.workOrderNo) {
            return a.workOrderNo.localeCompare(b.workOrderNo)
          }
          return a.material.localeCompare(b.material)
        })
      }
      
      analysisInfo = `勾选工单分析 (${checkedWorkOrderIds.length}个工单: ${checkedWorkOrderIds.join(', ')}) - 共分析 ${analysisResults.length} 个物料项目`
      
    } else {
      // 如果没有勾选工单，使用原有的分析逻辑（从SMIS工单接口）
      console.log('🔍 使用原有分析逻辑，分析工单:', workno)
      
      // 获取所有工单号列表
      const allWorkOrders = workOrders.value.map(order => order.orderno)
      let analysisWorkOrders = []
      
      // 处理不同类型的分析请求
      if (workno && typeof workno === 'object' && workno.type === 'level1') {
        // 一级标题分析
        const level1Data = workno.data
        const level1WorkOrders = []
        
        if (level1Data && level1Data.children) {
          level1Data.children.forEach(level2 => {
            if (level2.id) {
              level1WorkOrders.push(level2.id)
            }
          })
        }
        
        const matchedWorkOrders = level1WorkOrders.filter(orderNo => allWorkOrders.includes(orderNo))
        analysisWorkOrders = matchedWorkOrders
        
      } else if (workno && typeof workno === 'string') {
        // 二级或三级标题分析
        const hasMatchingWorkOrder = allWorkOrders.includes(workno)
        
        if (hasMatchingWorkOrder) {
          // 二级标题分析（工单号）
          analysisWorkOrders = [workno]
        } else {
          // 三级标题分析（工序分析），找到对应的工单号和工序ID
          let foundWorkOrder = null
          let workProcessId = null
          
          for (const level1 of hierarchicalData.value) {
            for (const level2 of level1.children) {
              for (const level3 of level2.children) {
                if (level3.id === workno) {
                  foundWorkOrder = level2.id
                  workProcessId = level3.title // 三级标题就是工序ID（如M01）
                  break
                }
              }
              if (foundWorkOrder) break
            }
            if (foundWorkOrder) break
          }
          
          if (foundWorkOrder && workProcessId) {
            // 对于三级标题分析，需要特殊处理
            console.log('🔍 三级标题工序分析:', { workOrderNo: foundWorkOrder, workProcessId: workProcessId })
            
            // 收集该工序的物料信息
            const workProcessMaterials = []
            
            try {
              const response = await getSMISWorkOrderMaterials(foundWorkOrder)
              
              if (response && response.success && response.data) {
                const workOrders = Array.isArray(response.data) ? response.data : [response.data]
                
                // 从工单的inputMaterialRequirements中筛选匹配的物料
                workOrders.forEach(workOrder => {
                  if (workOrder.inputMaterialRequirements && Array.isArray(workOrder.inputMaterialRequirements)) {
                    workOrder.inputMaterialRequirements.forEach(material => {
                      if (material.work) {
                        // 从work字段中提取第二个-之前的部分
                        const workParts = material.work.split('-')
                        if (workParts.length >= 2) {
                          const workPrefix = workParts[1] // 取第二个部分（如M01）
                          
                          // 检查是否与工序ID匹配
                          if (workPrefix === workProcessId) {
                            const requiredQty = parseFloat(material.quantity || material.qty || '0')
                            
                            workProcessMaterials.push({
                              workOrderNo: workOrder.orderno || foundWorkOrder,
                              materialCode: material.materialdefinition || '',
                              materialDescription: material.materialname || material.materialdefinition || '-',
                              spec: material.materialname || material.materialdefinition || '-',
                              requiredQuantity: requiredQty
                            })
                          }
                        }
                      }
                    })
                  }
                })
              }
            } catch (error) {
              console.error(`获取工单 ${foundWorkOrder} 的物料数据失败:`, error)
            }
            
            // 如果找到匹配的物料，进行齐套分析
            if (workProcessMaterials.length > 0) {
              // 先加载SMIS配料岛库存数据
              await loadSMISInventory()
              
              // 提取所有物料编码用于U9库存查询
              const materialCodes = [...new Set(workProcessMaterials.map(item => item.materialCode).filter(Boolean))]
              
              // 加载U9库存数据
              await loadU9Inventory(materialCodes)
              
              // 对每个物料进行齐套分析
              for (const materialItem of workProcessMaterials) {
                const materialCode = materialItem.materialCode
                const requiredQty = materialItem.requiredQuantity
                const spec = materialItem.spec
                const workOrderNo = materialItem.workOrderNo
                
                // 获取当前工单的masterplan（用于匹配SMIS配料岛数据）
                let masterplanForMatching = null
                const targetWorkOrder = workOrders.value.find(order => order.orderno === workOrderNo)
                if (targetWorkOrder) {
                  const originalMasterplan = targetWorkOrder.masterplan || ''
                  masterplanForMatching = originalMasterplan.trim()
                  const spaceIndex = masterplanForMatching.indexOf(' ')
                  if (spaceIndex !== -1) {
                    masterplanForMatching = masterplanForMatching.substring(0, spaceIndex)
                  }
                }
                
                // 在SMIS配料岛库存中查找匹配的物料
                let smisMatches = []
                if (masterplanForMatching) {
                  smisMatches = smisInventory.value.filter(item => {
                    const masterplanMatch = item.masterplancode === masterplanForMatching
                    const materialMatch = item.materialcode === materialCode
                    return masterplanMatch && materialMatch
                  })
                } else {
                  smisMatches = smisInventory.value.filter(item => 
                    item.materialcode === materialCode
                  )
                }
                
                // 计算SMIS配料岛总库存
                let smisTotal = 0
                smisMatches.forEach(item => {
                  if (typeof item.total === 'number') {
                    smisTotal += item.total
                  }
                })
                
                // 在U9库存中查找匹配的物料
                const u9Matches = u9Inventory.value.filter(item => 
                  item.ItemCode === materialCode || item.itemCode === materialCode
                )
                
                // 计算U9库存数量
                let u9StoreQty = 0
                u9Matches.forEach((item, index) => {
                  const dataArray = parseResponseData(item)
                  
                  if (dataArray.length > 0) {
                    dataArray.forEach((dataItem, dataIndex) => {
                      if (dataItem && typeof dataItem === 'object' && dataItem.StoreQty !== undefined) {
                        const storeQty = parseFloat(dataItem.StoreQty) || 0
                        u9StoreQty += storeQty
                      }
                    })
                  }
                })
                
                // 判断齐套状态
                let status = '未齐套'
                let statusClass = 'incomplete'
                let completed = 0
                let reasonTag = ''
                let lackQty = '0'
                
                if (smisTotal >= requiredQty) {
                  // 配料岛库存充足，已齐套
                  status = '已齐套'
                  statusClass = 'complete'
                  completed = requiredQty
                  reasonTag = ''
                  lackQty = '0'
                } else {
                  // 配料岛库存不足，需要查看U9库存
                  const totalAvailable = smisTotal + u9StoreQty
                  if (smisTotal > 0 && smisTotal < requiredQty) {
                    status = '部分齐套'
                    statusClass = 'partial'
                    if (totalAvailable >= requiredQty) {
                      reasonTag = '未领用'
                      completed = smisTotal
                      lackQty = '0'
                    } else {
                      reasonTag = '缺料'
                      completed = smisTotal
                      const shortageAmount = requiredQty - totalAvailable
                      lackQty = `${shortageAmount}`
                    }
                  } else if (smisTotal === 0) {
                    if (totalAvailable >= requiredQty) {
                      status = '未齐套'
                      statusClass = 'incomplete'
                      reasonTag = '未领用'
                      completed = 0
                      lackQty = '0'
                    } else {
                      status = '未齐套'
                      statusClass = 'incomplete'
                      reasonTag = '缺料'
                      completed = 0
                      const shortageAmount = requiredQty - totalAvailable
                      lackQty = `${shortageAmount}`
                    }
                  }
                }
                
                analysisResults.push({
                  workOrderNo: workOrderNo,
                  material: materialCode,
                  spec: spec,
                  required: requiredQty.toString(),
                  status: status,
                  statusClass: statusClass,
                  completed: completed.toString(),
                  reasonTag: reasonTag,
                  lackQty: lackQty,
                  u9StoreQty: u9StoreQty.toString(),
                  sortPriority: reasonTag === '缺料' ? 1 : (reasonTag === '未领用' ? 2 : 3)
                })
              }
              
              // 按照齐套状态排序：缺料 > 未领用 > 齐套
              analysisResults.sort((a, b) => {
                if (a.sortPriority !== b.sortPriority) {
                  return a.sortPriority - b.sortPriority
                }
                if (a.workOrderNo !== b.workOrderNo) {
                  return a.workOrderNo.localeCompare(b.workOrderNo)
                }
                return a.material.localeCompare(b.material)
              })
              
              // 设置分析信息
              analysisInfo = `工序 ${workProcessId} (工单 ${foundWorkOrder}) - 共分析 ${analysisResults.length} 个物料项目`
              
              // 直接设置分析结果，跳过后续的executeKitAnalysisForWorkOrders调用
              if (analysisResults.length > 0) {
                materialData.value = analysisResults
                currentAnalysisInfo.value = analysisInfo
              } else {
                // 如果没有匹配的物料，显示提示信息
                materialData.value = []
                currentAnalysisInfo.value = `工序 ${workProcessId} (工单 ${foundWorkOrder}) - 无匹配的物料项目`
              }
              
              // 提前返回，不执行后续的分析逻辑
              return
            } else {
              // 如果没有找到匹配的物料，显示空结果
              materialData.value = []
              currentAnalysisInfo.value = `工序 ${workProcessId} (工单 ${foundWorkOrder}) - 无匹配的物料项目`
              return
            }
          }
        }
      } else {
        // 全部分析
        analysisWorkOrders = allWorkOrders
      }
      
      // 使用原有的齐套分析逻辑
      const analysisResult = await executeKitAnalysisForWorkOrders(analysisWorkOrders)
      
      if (analysisResult.analysisResults && analysisResult.analysisResults.length > 0) {
        analysisResults = analysisResult.analysisResults
      }
      
      // 生成分析信息
      const clickedTitleInfo = getClickedTitleInfo(workno)
      let workOrderInfo = '全部工单'
      if (analysisWorkOrders && analysisWorkOrders.length === 1) {
        workOrderInfo = `工单 ${analysisWorkOrders[0]}`
      } else if (analysisWorkOrders && analysisWorkOrders.length > 1) {
        workOrderInfo = `${analysisWorkOrders.length}个工单 (${analysisWorkOrders.join(', ')})`
      }
      
      analysisInfo = `${clickedTitleInfo} - ${workOrderInfo} - 共分析 ${analysisResults.length} 个物料项目`
    }
    
    // 设置分析结果
    if (analysisResults.length > 0) {
      materialData.value = analysisResults
      currentAnalysisInfo.value = analysisInfo
    } else {
      // 如果没有分析结果，显示默认信息
      materialData.value = [
        {
          material: '无分析结果',
          spec: '-',
          required: '-',
          status: '待分析',
          statusClass: 'incomplete',
          completed: '-',
          reasonTag: '系统提示',
          lackQty: '0',
          u9StoreQty: '0'
        }
      ]
      
      currentAnalysisInfo.value = analysisInfo || '无可用的分析结果'
    }
    
  } catch (error) {
    console.error('齐套分析失败:', error)
    // 显示错误信息
    materialData.value = [
      {
        material: '错误',
        spec: '分析失败',
        required: '-',
        status: '错误',
        statusClass: 'incomplete',
        completed: '-',
        reasonTag: '系统错误',
        lackQty: '0',
        u9StoreQty: '0'
      }
    ]
    
    currentAnalysisInfo.value = '分析过程中发生错误'
  }
  
  // 计算表格应该显示的位置
  if (event) {
    nextTick(() => {
      const button = event.target
      const leftPanel = document.querySelector('.left-panel')
      const rightPanel = document.querySelector('.right-panel')
      
      if (leftPanel && rightPanel) {
        // 获取按钮相对于左侧面板的位置
        const buttonRect = button.getBoundingClientRect()
        const leftPanelRect = leftPanel.getBoundingClientRect()
        
        // 计算相对位置，减去标题区域的高度
        const relativeTop = buttonRect.top - leftPanelRect.top
        const statusInfoHeight = 80 // 齐套状态说明区域的大概高度
        
        // 设置表格的顶部偏移量
        tableTopOffset.value = Math.max(0, relativeTop - statusInfoHeight)
      }
    })
  } else {
    // 如果没有事件（比如整体齐套分析），表格显示在顶部
    tableTopOffset.value = 0
  }
}

// 拖拽滚动相关方法
const startDrag = (event, element) => {
  event.preventDefault()
  isDragging.value = true
  dragStartX.value = event.clientX
  dragStartScrollLeft.value = element.scrollLeft
  currentDragElement.value = element
  
  // 修改鼠标样式和添加拖拽状态类
  element.style.cursor = 'grabbing'
  element.classList.add('dragging')
  
  // 添加全局事件监听
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
  
  // 阻止默认的文本选择行为
  document.body.style.userSelect = 'none'
}

const onDrag = (event) => {
  if (!isDragging.value || !currentDragElement.value) return
  
  event.preventDefault()
  const deltaX = event.clientX - dragStartX.value
  currentDragElement.value.scrollLeft = dragStartScrollLeft.value - deltaX
}

const stopDrag = () => {
  if (currentDragElement.value) {
    currentDragElement.value.style.cursor = 'grab'
    currentDragElement.value.classList.remove('dragging')
  }
  
  isDragging.value = false
  currentDragElement.value = null
  
  // 移除全局事件监听
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
  
  // 恢复文本选择
  document.body.style.userSelect = ''
}

// 组件挂载时加载数据
onMounted(() => {
  // 立即显示界面，工单数据在后台加载
  loading.value = false
  loadWorkOrders()
})

// 组件卸载时清理事件监听
onBeforeUnmount(() => {
  if (isDragging.value) {
    stopDrag()
  }
})
</script>

<style scoped>
.kit-analysis-container {
  padding: 0;
  width: 100%;
  max-width: none;
  margin: 0;
  background: #f8f9fa;
  min-height: 100vh;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #ffffff;
  border-bottom: 1px solid #e9ecef;
  padding: 16px 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header h2 {
  font-size: 20px;
  color: #343a40;
  margin: 0;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.upload-btn, .refresh-btn, .back-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  border: 1px solid transparent;
}

.upload-btn:hover, .refresh-btn:not(:disabled):hover, .back-btn:hover {
  background: #5a6268;
  transform: translateY(-1px);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.upload-btn {
  background: #007bff;
}

.upload-btn:hover {
  background: #0056b3;
}

.back-btn {
  background: #dc3545;
}

.back-btn:hover {
  background: #c82333;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-panel {
  flex: 0 0 400px;
  background: #ffffff;
  border-right: 1px solid #e9ecef;
  overflow-y: auto;
  padding: 16px;
}

.right-panel {
  flex: 1;
  background: #ffffff;
  overflow-y: auto;
  padding: 16px;
  position: relative;
}

.work-order-tree {
  margin-bottom: 16px;
}

/* 一级层次样式 */
.level1-section {
  margin-bottom: 8px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #dee2e6;
  transition: all 0.2s ease;
}

.level1-section:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.level1-item {
  background: #f8f9fa;
  color: #495057;
  font-weight: 600;
  padding: 12px 16px;
  transition: all 0.2s ease;
  border-bottom: 1px solid #dee2e6;
}

.level1-item:hover {
  background: #e9ecef;
}

.level1-title {
  flex-grow: 1;
  font-size: 14px;
  white-space: nowrap;
  overflow-x: hidden;
  overflow-y: hidden;
  text-overflow: unset;
  cursor: grab;
  position: relative;
  margin-right: 10px;
}



.level1-title:active {
  cursor: grabbing;
}

.level1-title:hover {
  background-color: rgba(108, 117, 125, 0.05);
}

.level1-title div {
  display: inline-block;
  min-width: 100%;
  padding: 0 2px;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.level1-title.dragging {
  cursor: grabbing !important;
  background-color: rgba(108, 117, 125, 0.1);
}

.level1-title:active div {
  pointer-events: none;
}

/* 二级层次样式 */
.level2-container {
  background: #ffffff;
  padding: 8px;
}

.level2-section {
  margin-bottom: 6px;
}

.level2-item {
  background: #f8f9fa;
  color: #495057;
  font-weight: 500;
  padding: 10px 14px;
  border-radius: 6px;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.level2-item:hover {
  background: #e9ecef;
  transform: translateX(4px);
}

.level2-title {
  flex-grow: 1;
  font-size: 13px;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  text-overflow: unset;
  cursor: grab;
  position: relative;
  margin-right: 10px;
}

.level2-title::-webkit-scrollbar {
  height: 4px;
}

.level2-title::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.level2-title::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.level2-title::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.level2-title:active {
  cursor: grabbing;
}

.level2-title:hover {
  background-color: rgba(108, 117, 125, 0.05);
}

.level2-title div {
  display: inline-block;
  min-width: 100%;
  padding: 0 2px;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.level2-title.dragging {
  cursor: grabbing !important;
  background-color: rgba(108, 117, 125, 0.1);
}

.level2-title:active div {
  pointer-events: none;
}

/* 三级层次样式 */
.level3-container {
  background: #ffffff;
  margin: 4px 0;
  border-radius: 6px;
  padding: 6px;
}

.level3-item {
  background: #ffffff;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 8px 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
  transition: all 0.2s ease;
}

.level3-item:hover {
  background: #f8f9fa;
  transform: translateX(6px);
  border-color: #adb5bd;
}

.level3-title {
  font-weight: 600;
  color: #007bff;
  min-width: 60px;
  font-size: 12px;
  white-space: nowrap;
  flex-shrink: 0;
}

.workname {
  flex-grow: 1;
  color: #6c757d;
  font-size: 11px;
  font-weight: 400;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
}

.loading {
  text-align: center;
  padding: 60px;
  color: #6c757d;
  font-size: 16px;
  font-weight: 500;
  background: #ffffff;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.loading-indicator {
  text-align: center;
  padding: 40px 20px;
  color: #6c757d;
  font-size: 14px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.loading-indicator p {
  margin: 0;
  font-weight: 500;
}

.tree-item {
  display: flex;
  align-items: center;
  padding: 0;
  gap: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 6px;
  min-height: 40px;
}

.arrow {
  color: #6c757d;
  font-size: 12px;
  transition: transform 0.2s ease;
  width: 16px;
  text-align: center;
}

.arrow.expanded {
  transform: rotate(90deg);
}

.analysis-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  font-weight: 500;
  transition: all 0.2s ease;
  white-space: nowrap;
  flex-shrink: 0;
  min-width: 70px;
}

.analysis-btn:hover {
  background: #218838;
  transform: translateY(-1px);
}

.analysis-btn:disabled {
  background-color: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.analysis-btn:disabled:hover {
  background-color: #e9ecef;
  transform: none;
  box-shadow: none;
}

.table-header {
  background: #f8f9fa;
  color: #495057;
  padding: 12px 16px;
  border-radius: 8px 8px 0 0;
  text-align: center;
  border: 1px solid #dee2e6;
  border-bottom: none;
}

.table-header h3 {
  font-size: 16px;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.analysis-info {
  font-size: 13px;
  color: #6c757d;
  background: #e9ecef;
  padding: 6px 12px;
  border-radius: 4px;
  margin-top: 8px;
  display: inline-block;
}

.info-label {
  font-weight: 500;
  color: #495057;
}

.info-content {
  font-weight: 400;
  margin-left: 4px;
}

.no-analysis-hint {
  text-align: center;
  padding: 60px 30px;
  color: #6c757d;
  font-size: 14px;
  font-weight: 400;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #dee2e6;
}

.no-analysis-hint p {
  margin: 0;
}

.material-table-container {
  transition: margin-top 0.3s ease;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  border: 1px solid #dee2e6;
}

.material-table {
  overflow-x: auto;
}

.material-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

.material-table th,
.material-table td {
  border: 1px solid #dee2e6;
  padding: 8px 6px;
  text-align: center;
  background: #ffffff;
  white-space: nowrap;
  overflow: hidden;
}

.material-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
  font-size: 12px;
}

/* 可拖拽列的表头样式 */
.material-table th[title*="可拖拽"] {
  background: #e8f4fd;
  color: #0066cc;
  cursor: help;
  position: relative;
}

.material-table th[title*="可拖拽"]:hover {
  background: #d1ecf1;
}

.material-table tbody tr:hover {
  background: #f8f9fa;
}

/* 表格列宽控制 */
.workorder-col {
  width: 10%;
  max-width: 120px;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  text-overflow: unset;
  cursor: grab;
  position: relative;
}

.workorder-col::-webkit-scrollbar {
  height: 4px;
}

.workorder-col::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.workorder-col::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.workorder-col::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.workorder-col:active {
  cursor: grabbing;
}

.material-col {
  width: 15%;
  max-width: 150px;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  text-overflow: unset;
  cursor: grab;
  position: relative;
}

.material-col::-webkit-scrollbar {
  height: 4px;
}

.material-col::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.material-col::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.material-col::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 添加拖拽提示样式 */
.material-col:active {
  cursor: grabbing;
}

.spec-col {
  width: 12%;
  max-width: 120px;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  text-overflow: unset;
  cursor: grab;
  position: relative;
}

.spec-col::-webkit-scrollbar {
  height: 4px;
}

.spec-col::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.spec-col::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.spec-col::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 添加拖拽提示样式 */
.workorder-col:active {
  cursor: grabbing;
}

.spec-col:active {
  cursor: grabbing;
}

.workorder-col:hover,
.material-col:hover,
.spec-col:hover {
  background-color: rgba(108, 117, 125, 0.05);
}

.workorder-col div,
.material-col div,
.spec-col div {
  display: inline-block;
  min-width: 100%;
  padding: 0 2px;
  user-select: none; /* 防止拖拽时选中文本 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

/* 拖拽状态下的全局样式 */
.workorder-col.dragging,
.material-col.dragging,
.spec-col.dragging {
  cursor: grabbing !important;
  background-color: rgba(108, 117, 125, 0.1);
}

/* 拖拽时禁用文本选择 */
.workorder-col:active div,
.material-col:active div,
.spec-col:active div {
  pointer-events: none;
}
.quantity-col {
  width: 8%;
  max-width: 80px;
  white-space: nowrap;
}

.status-col {
  width: 10%;
  max-width: 100px;
  font-weight: 600;
  white-space: nowrap;
}

.completed-col {
  width: 8%;
  max-width: 80px;
  white-space: nowrap;
}

.reason-col {
  width: 10%;
  max-width: 100px;
  font-weight: 500;
  white-space: nowrap;
}

.unused-col {
  width: 12%;
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
}

.remaining-col {
  width: 15%;
  max-width: 150px;
  white-space: nowrap;
}

.loading-analysis {
  text-align: center;
  padding: 60px 30px;
  color: #007bff;
  font-size: 14px;
  font-weight: 500;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.loading-analysis p {
  margin: 0;
}

.error-analysis {
  text-align: center;
  padding: 60px 30px;
  color: #dc3545;
  font-size: 14px;
  font-weight: 500;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.error-analysis p {
  margin: 0;
}

.error-state {
  background: #ffffff;
  border-radius: 8px;
  padding: 40px;
  border: 1px solid #dee2e6;
  text-align: center;
  max-width: 600px;
  margin: 40px auto;
}

.error-content h3 {
  color: #dc3545;
  font-size: 20px;
  margin-bottom: 16px;
  font-weight: 600;
}

.error-content p {
  color: #6c757d;
  font-size: 14px;
  margin-bottom: 12px;
  line-height: 1.5;
}

.error-content ul {
  text-align: left;
  color: #6c757d;
  margin: 16px 0;
  padding-left: 20px;
}

.error-content li {
  margin-bottom: 6px;
  line-height: 1.4;
}

.error-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin: 24px 0;
  flex-wrap: wrap;
}

.retry-btn {
  background: #6c757d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.retry-btn:hover {
  background: #5a6268;
  transform: translateY(-1px);
}

.retry-btn .btn-icon {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-panel {
    flex: none;
    max-height: 300px;
  }
  
  .right-panel {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
    padding: 12px 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .left-panel {
    padding: 12px;
  }
  
  .right-panel {
    padding: 12px;
  }
  
  .material-table th,
  .material-table td {
    padding: 6px 4px;
    font-size: 11px;
  }
  
  .level1-item,
  .level2-item {
    padding: 10px 12px;
  }
  
  .level3-item {
    padding: 6px 10px;
  }
}

/* 滚动条样式 */
.left-panel::-webkit-scrollbar,
.right-panel::-webkit-scrollbar {
  width: 6px;
}

.left-panel::-webkit-scrollbar-track,
.right-panel::-webkit-scrollbar-track {
  background: #f8f9fa;
  border-radius: 3px;
}

.left-panel::-webkit-scrollbar-thumb,
.right-panel::-webkit-scrollbar-thumb {
  background: #dee2e6;
  border-radius: 3px;
}

.left-panel::-webkit-scrollbar-thumb:hover,
.right-panel::-webkit-scrollbar-thumb:hover {
  background: #adb5bd;
}
</style>
